package com.zeny.express.framework.webapp.support;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletContext;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

public class ModuleManager {

	protected static final Logger LOGGER = LoggerFactory
			.getLogger(ModuleManager.class);

	private static PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

	private static final String PACKAGE_PREFIX = "com/zeny/express/module/";

	private static final String TILES_FROM = "/META-INF/tiles/";

	private static final String TILES_TO = "/WEB-INF/tiles/";

	private static final String PAGES_FROM = "/META-INF/pages/";

	private static final String PAGES_TO = "/WEB-INF/pages/";

	private ModuleManager() {
	}

	/**
	 * 导出所有资源 export
	 * 
	 * @param servletContext
	 * @return void
	 * @since:0.6
	 */
	public static void export(ServletContext servletContext) {
		// 导出TILES页面
		export(servletContext, TILES_FROM, TILES_TO);
		// 导出JSP页面
		export(servletContext, PAGES_FROM, PAGES_TO);
	}

	/**
	 * 导出资源 export
	 * 
	 * @param servletContext
	 * @param from
	 * @param to
	 * @return void
	 */
	private static void export(ServletContext servletContext, String from,
			String to) {
		try {
			LOGGER.info("[Framework] servlet root dir: "
					+ servletContext.getRealPath("/"));

			Resource[] resources = resolver.getResources("classpath*:"
					+ PACKAGE_PREFIX + "**" + from + "*");
			if (resources != null && resources.length > 0) {
				for (Resource resource : resources) {
					try {
						String path = resource.getURL().getPath();

						int j = path.lastIndexOf(from);

						String pathHeader = path.substring(0, j);

						int i = pathHeader.lastIndexOf('/');
						String module = path.substring(i + 1, j);
						String page = path.substring(j + from.length());
						String dist = to + module + "/" + page;

						File file = new File(servletContext.getRealPath(dist));
						if (!file.getName().matches("^.*[.].*$")) {
							File dir = new File(file.getPath() + "\\"
									+ File.separator);
							// 先创建目录
							if (!dir.exists()) {
								boolean b = file.mkdirs();
								if (!b) {
									LOGGER.error("create dir failure!");
								}
								LOGGER.debug("[Framework] create dir: " + dir);
							}
						}
						File dir = file.getParentFile();
						if (!dir.exists()) {
							boolean b = dir.mkdirs();
							if (!b) {
								LOGGER.error("create dir failure!");
							}
							LOGGER.debug("[Framework] create dir: " + dir);
						}
						LOGGER.info("[Framework] release resource: " + dist);
						OutputStream out = new FileOutputStream(file);
						InputStream in = resource.getInputStream();
						IOUtils.copy(in, out);

						// 设置释放文件的最后修改时间
						file.setLastModified(resource.lastModified());

					} catch (Exception e) {
						LOGGER.error(e.getMessage(), e);
					}
				}
			}
		} catch (Exception e) {
			throw new IllegalStateException(e.getMessage(), e);
		}
	}
}
